import axios, {
  AxiosResponse,
  AxiosRequestConfig,
} from 'axios';

import { message } from 'antd';

const Api = axios.create({
  baseURL: '/api'
});

const getStore = () => g_app._store;

export const getToken = () => {
  const store = getStore();
  return store.getState().user.token;
};

const authCode = [20004];

const exitApp = () => {
  message.error('登录已失效,请重新登录');
  getStore().dispatch({ type: 'user/resetState' });
};

const response = (_res_: AxiosResponse) => {
  const { data, status } = _res_;
  const { code = status, data: _data } = data;

  /*强制弹出登录*/
  if (authCode.includes(code)) setTimeout(exitApp);
  return code === 200 ? Promise.resolve(_data) : Promise.reject(data);
};

const request = (_req_: AxiosRequestConfig) => {
  const { headers } = _req_;
  const token = getToken();
  if (token) headers['Authorization'] = `Bearer ${token}`;
  return _req_;
};

Api.interceptors.request.use(request);
Api.interceptors.response.use(response);

export default Api;
